package com.candy.common.exception;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.candy.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 异常处理
 * @author Lenovo
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler
{
	/**
	 * 业务异常
	 */
	@ExceptionHandler(BaseException.class)
	public R baseException(BaseException e)
	{
		if (StringUtils.checkValNull(e.getCode()))
		{
			return R.error(e.getMessage());
		}
		return R.error(e.getCode(), e.getMessage());
	}
	/**
	 * 业务异常
	 */
	@ExceptionHandler(BusinessException.class)
	public R businessException(BusinessException e)
	{
		if (StringUtils.checkValNull(e.getCode()))
		{
			return R.error(e.getMessage());
		}
		return R.error(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(NoHandlerFoundException.class)
	public R handlerNoFoundException(Exception e)
	{
		log.error(e.getMessage(), e);
		return R.error(HttpStatus.NOT_FOUND, "路径不存在，请检查路径是否正确");
	}

	@ExceptionHandler(Exception.class)
	public R handleException(Exception e)
	{
		log.error(e.getMessage(), e);
		return R.error(e.getMessage());
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(BindException.class)
	public R validatedBindException(BindException e)
	{
		log.error(e.getMessage(), e);
		String message = e.getAllErrors()
						  .get(0)
						  .getDefaultMessage();
		return R.error(message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Object validExceptionHandler(MethodArgumentNotValidException e)
	{
		log.error(e.getMessage(), e);
		String message = e.getBindingResult()
						  .getFieldError()
						  .getDefaultMessage();
		return R.error(message);
	}

}
